package com.senriot.quickup.service.mapper

import com.senriot.cloud.common.IEntityMapper
import com.senriot.quickup.domain.AdSchedule
import com.senriot.quickup.domain.QAd
import com.senriot.quickup.domain.QDevice
import com.senriot.quickup.repository.AdRepository
import com.senriot.quickup.repository.DeviceRepository
import com.senriot.quickup.service.dto.AdScheduleDTO
import org.mapstruct.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier

@Mapper(
    componentModel = "spring",
    uses = [AdMapper::class, DeviceMapper::class],
    nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE
)
abstract class AdScheduleMapper : IEntityMapper<AdScheduleDTO, AdSchedule>
{


    @Qualifier("deviceRepository")
    @Autowired
    private lateinit var deviceRepository: DeviceRepository
    @Qualifier("adRepository")
    @Autowired
    private lateinit var adRepository: AdRepository


    @Mappings(
        Mapping(target = "ads", ignore = true),
        Mapping(target = "devices", ignore = true)
    )
    abstract override fun toEntity(dto: AdScheduleDTO): AdSchedule

    @AfterMapping
    fun calledWithSourceAndTarget(dto: AdScheduleDTO, @MappingTarget entity: AdSchedule)
    {
        entity.ads = adRepository.findAll(QAd.ad.id.`in`(dto.ads)).toMutableList()
        entity.devices = deviceRepository.findAll(QDevice.device.id.`in`(dto.devices)).toMutableList()
    }
}
